package com.carpedil.order.service.impl;

import com.carpedil.common.dto.OrderDTO;
import com.carpedil.order.entity.Order;
import com.carpedil.order.mapper.OrderMapper;
import com.carpedil.order.service.OrderService;
import com.carpedil.util.StringUtil;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/** @author Administrator */
@Service
public class OrderServiceImpl implements OrderService {
  @Autowired OrderMapper mapper;
  @Autowired RabbitTemplate rabbitTemplate;

  RabbitTemplate.ConfirmCallback callback =
      (CorrelationData correlationData, boolean b, String s) -> {
        if (b) {
          assert correlationData != null;
          String orderId = correlationData.getId();
          // 放入队列成功,修改订单状态 购票成功,正在出票 code: 1
          mapper.updateOrderStatus(orderId, StringUtil.BOOKING_COMPLETED);
        }
      };

  @Override
  public String save(OrderDTO dto) {
    Order order = new Order();
    BeanUtils.copyProperties(dto, order);
    mapper.saveOrder(order);
    // 开启手动确认
    rabbitTemplate.setMandatory(true);
    // 绑定回调函数
    rabbitTemplate.setConfirmCallback(callback);
    // 组装关联数据
    CorrelationData correlationData = new CorrelationData(dto.getOrderId());
    // 放入订单队列
    rabbitTemplate.convertAndSend("orderExchange", "j178.order", dto, correlationData);
    return StringUtil.BOOKING_FINISHED;
  }

  @Override
  public Integer updateStatusByName(String orderId, Integer code) {
    return mapper.updateOrderStatus(orderId, code);
  }

  @Override
  public List<Order> getOrderList() {
    return mapper.list();
  }
}
